package com.hpf.spider.utils;

import org.apache.commons.lang3.StringUtils;
import org.brotli.dec.BrotliInputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BrotliDecompressor {
    /**
     * 解压缩 Brotli 压缩的数据
     *
     * @param compressedData 压缩后的数据
     * @return 解压缩后的数据
     * @throws IOException 如果解压缩失败
     */
    public static String decompress(byte[] compressedData) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
             BrotliInputStream brotliInputStream = new BrotliInputStream(byteArrayInputStream);
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = brotliInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            return new String(byteArrayOutputStream.toByteArray(), "utf-8");
        }catch (Exception e){
            e.printStackTrace();
            return StringUtils.EMPTY;
        }
    }

}
